/* eslint-disable no-undef */

 import Logger from '../base/logger'
 import {IvcsError} from "../base/error";

// key 地图授权密钥
class MapLocation {
    constructor(key) {
        this.key = key || "3b4d2ba929f223fc6109121b51e47693";
        this.src = `https://webapi.amap.com/maps?v=1.4.15&key=${this.key}`;
        this.loadScript(this.src);
    }

    // 动态加载 JS
    loadScript(src) {
        if (!this.key) {
            Logger.info("ivcs-js-sdk:定位未开启,key is empty", new Date());
            return 
        }
        let head = document.getElementsByTagName('head')[0];
        let script = document.createElement('script');
        script.type = 'text/javascript';
        script.src = src || '';
        head.appendChild(script);
        script.onload = function () {
            Logger.info("ivcs-js-sdk:地图 API 加载完成", new Date().toISOString());
        }
    }

    // 高德地图
    getGaoDeLocation(onSuccess, onFailed, mapTimeout) {
        let waitTimeout = mapTimeout ? mapTimeout : 10000;
        try {
            AMap.plugin('AMap.Geolocation', function () {
                let geolocation = new AMap.Geolocation({
                    // 是否使用高精度定位，默认：true
                    enableHighAccuracy: true,
                    // 设置定位超时时间，默认：无穷大
                    timeout: waitTimeout,
                    // 定位按钮的停靠位置的偏移量，默认：Pixel(10, 20)
                    buttonOffset: new AMap.Pixel(10, 20),
                    //  定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false
                    zoomToAccuracy: true,
                    //  定位按钮的排放位置,  RB表示右下
                    buttonPosition: 'RB'
                })
                geolocation.getCurrentPosition();
                let result = {};
                AMap.event.addListener(geolocation, 'complete', (res => {
                    result.code = 200;
                    result.data = res;
                    result.type = "success";
                    onSuccess(result);
                }));
                AMap.event.addListener(geolocation, 'error', (err => {
                    if (err.message.indexOf('time out') != -1) {
                       result.code = 408;
                       result.type = "timeout";
                       result.reason = "获取地理位置信息超时";
                    } else if (err.message.indexOf('permission denied') != -1) {
                       result.code = 407;
                       result.type="permissionDenied";
                       result.reason = "访问权限拒绝";
                    }
                    let error = new IvcsError('80001', `request location is fail${JSON.stringify(result)}`);
                    Logger.error('ivcs-js-sdk:getGaoDeLocation error', error, new Date())
                    onFailed(result)
                }));
            })
        } catch (e) {
            Logger.error('ivcs-js-sdk:getGaoDeLocation catch error', e, new Date());
        }
    }
}

export { MapLocation };
